package keter.web.controller._experiment;

import java.io.InputStream;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import keter.KeterConfig;
import keter.framework.exception.KeterFileException;
import keter.framework.model.FileItem;
import keter.framework.web.upload.UploadItem;
import keter.framework.web.upload.UploadUtil;
import keter.web.controller.base.KeterBaseController;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;
import org.springframework.web.servlet.ModelAndView;

import com.google.common.collect.Maps;
import com.jfinal.kit.PropKit;


/**
 * <p>Class       : app.controller.IndexLoginController
 * <p>Descdription: 首页和登录控制逻辑的统一处理
 *
 * @author  gulixing@msn.com
 * @version 1.0.0
 */
@Controller
@RequestMapping("keter/exp/upload")
public class ExpUploadController extends KeterBaseController {
    /**
     * Logger for this class
     */
    private static final Logger logger = LoggerFactory.getLogger(ExpUploadController.class);
   
    /*与 @RequestMapping中的内容保持一致 */
	private static final String path = "keter/exp/upload";
		 
    /**
	 * <p>Method ：update
	 * <p>Description : 访问文件上传页面
	 * @param model
	 * @return 
	 * @author  gulixing@msn.com
	 * @version 1.0.0
	 */
	@RequestMapping(value = Routes.Index, method = RequestMethod.GET)
	public String upload(Model model) {
		model.addAttribute(new UploadItem());
		model.addAttribute("size", PropKit.get("upload.type1.max")+"MB");
		model.addAttribute("ext", PropKit.get("upload.type1.ext"));
		return to_(path)+"index";
	}
	
	/**
	 * <p>Method ：update
	 * <p>Description : 更新报告
	 * @param uploadItem
	 * @param model
	 * @param request
	 * @return 
	 * @author  gulixing@msn.com
	 * @version 1.0.0
	 */
	@RequestMapping(value = Routes.Upload, method = RequestMethod.POST)
    public ModelAndView update(UploadItem uploadItem, Model model, HttpServletRequest request) {
		MultipartHttpServletRequest req = (MultipartHttpServletRequest)request;
		String redirectUrl = Routes.Index;
		Map<String, String> map = Maps.newHashMap();
		//上传数据
        try {
            MultipartFile file = uploadItem.getData();
            FileItem fi = null;
            if (file.getSize() > 0) {
                //logger.info("size::" + file.getSize());
        	     String ext = PropKit.get("upload.type1.ext");
        		 Long size = Long.valueOf(PropKit.get("upload.type1.max"))*1024*1024;
            	try {
					UploadUtil.validateUploadFile(file,ext,size);
				} catch (KeterFileException kve) {
					model.addAttribute("updateMessage", kve.getMessage());
					map.put("message", kve.getMessage());
		            return new ModelAndView(path+"/upload_result",map);
				}
                InputStream inputStream = file.getInputStream();         
                //写入磁盘文件
                String subFolder = "type1";
                String fileId = UploadUtil.writeRandomNameFile(subFolder, inputStream);
                fi = new FileItem();
                fi.set("fileId", fileId);
                //保存文件原名
                fi.set("name", file.getOriginalFilename());
                //保存文件目录
                fi.set("path",subFolder);
                fi.save();
            }
            model.addAttribute("updateMessage", "保存成功！");
            map.put("message","保存成功！");
            map.put("fileId",fi.getStr("fileId"));
        } catch (Exception e) {
            model.addAttribute("updateMessage", "文件上传失败！");
            map.put("message", "文件上传失败！");
        	logger.error("文件上传失败，异常信息:",e);
            return new ModelAndView(path+"/upload_result",map);
        }		
        return new ModelAndView(path+"/upload_result",map);
//        return redirectToUrl(redirectUrl);
    }
	
	@RequestMapping(value = Routes.Download, method = RequestMethod.GET)
	//注意: @PathVariable 中的变量名必须同@RequestMapping中value=xxx中的变量通配符保持一致
	//否则会出现"HTTP ERROR 400 Bad Request"
	public void download(HttpServletRequest request, HttpServletResponse response, @PathVariable String fileId) throws Exception {
		FileItem fi = FileItem.dao.findByFileId(fileId);	
		if(fi!=null){
	       //对数据库中有内容但磁盘文件无法访问的情况给出明确的用户提示
		   UploadUtil.makeDownload(request,response,fi);
		}
        //如果无法根据fileId从数据库中找到记录说明客户端手动修改了fileId
		//此种情况属于非正常行为，不做特殊处理
		return;
	}
}